<?php

namespace app\common\service\StoreService;

use app\model\BbcModel\BusinessLevel;
use app\model\BbcModel\StoreManager;
use app\model\BbcModel\StoreMember;
use think\facade\Db;
use app\Normal;
use app\model\BbcModel\Store;
use app\model\BbcModel\StoreAuthGroup;
use app\model\BbcModel\Channel;
use app\model\BbcModel\ChannelWx;
use app\model\BbcModel\Host;
use app\model\BbcModel\Manager;
use app\model\BbcModel\AuthGroup;
use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\Order;



/**
 * 分销商业务
 * @author linan
 */
class StoreManageService
{

    /**
     * 分销商列表
     * @param array $param
     * @return array
     */
    public function storeList(array $param)
    {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $p=($page-1)*$limit;
        $where=[];
        //服务商id
        if(!empty($param['sp_id'])){
            $where[]=['s.sp_id','in',$param['sp_id']];
        }
        //渠道商id
        if(!empty($param['cid'])){
            $where[]=['s.cid','in',$param['cid']];
        }
        //渠道商id
        if(!empty($param['cb_id'])){
            $where[]=['s.cb_id','in',$param['cb_id']];
        }
        //店铺名字
        if(!empty($param['mn_sid'])){
            $where[]=['s.id','in',$param['mn_sid']];
        }
        //注册手机号
        if(!empty($param['mobile'])){
            $where[]=['s.mobile','like','%'.$param['mobile'].'%'];
        }
        //名字或者手机模糊匹配
        if(!empty($param['search'])){
            $where[]=['s.mobile|s.store_name','like','%'.$param['search'].'%'];
        }
        //注册时间
        if(!empty($param['cd_start'])){
            $where[]=['s.cd','>=',strtotime($param['cd_start'])];
        }
        if(!empty($param['cd_end'])){
            $where[]=['s.cd','<=',strtotime($param['cd_end'])];
        }
        //状态
        if(isset($param['status']) && $param['status'] !==''){
            $where[] = ['s.status', '=', $param['status']];
        }
        //类型
        if(!empty($param['type'])){
            $where[]=['s.type','=',$param['type']];
        }
        $fields="s.id,s.cid,s.sp_id,s.cb_id,s.mobile,s.store_name,s.status,s.check_status,s.type,s.all_sell,s.link_man,s.cd,sp.name as service_name,cb.name as channel_name,cb.level_id,s.qrcode,s.recommend_name,s.recommend_idcard";
        $level=BusinessLevel::instance()->lists(['_fields_'=>'id,level_name']);
        $level=array_column($level,'level_name','id');
        $list=Store::instance()->alias('s')
            ->field($fields)
            ->join('service_provider sp','sp.id=s.sp_id')
            ->join('channel_business cb','cb.id=s.cb_id')
            ->where($where)
            ->order('s.id desc')
            ->limit($p, $limit)
            ->select()
            ->toArray();
        foreach ($list as $k=>$v){
            $list[$k]['channel_level']=$level[$v['level_id']];
            $list[$k]['type_name']=$v['type']==1?'线上商城':'O2O店铺';
            $list[$k]['status_name']=$v['status']==1?'启用':'禁用';
            $list[$k]['check_status_name']=$v['check_status']==1?'已审核':($v['check_status']==2?'审核失败':'待审核');
            $list[$k]['order_number']=Order::instance()->countNum(['mn_sid'=>$v['id'],'pay_status'=>1]);
            $list[$k]['member']=StoreMember::instance()->countNum(['mn_sid'=>$v['id']]);
            $list[$k]['vip']=StoreMember::instance()->countNum([['mn_sid','=',$v['id']],['vip_expired','>',time()]]);
            $list[$k]['cd']=date('Y-m-d H:i:s',$v['cd']);
        }
        $num=Store::instance()->alias('s')
            ->join('service_provider sp','sp.id=s.sp_id')
            ->join('channel_business cb','cb.id=s.cb_id')
            ->where($where)
            ->count();
        $data['total']=$num;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }

    /**
     * 编辑分销商
     */
    public function editStore(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"店铺id必传");
        }
        $data=[
            'recommend_name'    => $param['recommend_name']??'',
            'recommend_idcard'  => $param['recommend_idcard']??'',
        ];
        Store::instance()->edit(['id'=>$param['id']],$data);
        return Normal::returnCode(Normal::SUC,"编辑成功");
    }



    /**
     * 分销商列表下拉菜单
     * @param array $param
     * @return array
     */
    public function storeSelectList(array $param)
    {
        $where=[
            ['check_status','=',1],
            '_fields_'=>'id,store_name,mobile'
        ];
        //服务商id
        if(!empty($param['sp_id'])){
            $where[]=['sp_id','=',$param['sp_id']];
        }
        //渠道商id
        if(!empty($param['cb_id'])){
            
            $where[]=is_array($param['cb_id'])?['cb_id','in',$param['cb_id']]:['cb_id','=',$param['cb_id']];
        }
        if(!empty($param['cid'])){
            $where[]=['cid','=',$param['cid']];
        }
        $list=Store::instance()->lists($where);
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }
    
    /**
     * 禁用店铺
     * @param array $param
     * @return array
     */
    public function changeStorestatus(array $param):array {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"店铺id必传");
        }
        $where=[['id','=',$param['id']]];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }
        if(isset($param['status'])&&$param['status']!==''){
            $editdata=['status'=>$param['status'],'md'=>time()];
        }else{
            return Normal::returnCode(Normal::FAIL,"status 必传");
        }
        $store= Store::instance()->info($where);
        if(empty($store)){
            return Normal::returnCode(Normal::FAIL,"店铺不存在");
        }
        $result= Store::instance()->edit(['id'=>$param['id']], $editdata);
        if($result){
            return Normal::returnCode(Normal::SUC,"修改成功");
        }else{
            return Normal::returnCode(Normal::FAIL,"修改失败");
        }
    }

    /**
     * 分销商审核
     * @param array $param
     * @return array
     */
    public function checkStore(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数分销商id");
        }
        if(empty($param['op'])){
            return Normal::returnCode(Normal::FAIL,"操作参数错误");
        }
        $info=Store::instance()->info(['id'=>$param['id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"审核的分销商不存在");
        }
        if($info['is_pay']!=1){
            return Normal::returnCode(Normal::FAIL,"该店铺还未支付,不能审核");
        }
        if($param['op']==1){
            $args = [
                'mobile'   => $info['mobile'],
            ];
            $checkMember = callTcpService('bbcUserAccountRegister',$args);
            if($checkMember['code']==200){
                $mid=$checkMember['data']['mid'];
            }else{
                return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$checkMember['msg']);
            }
            $group['name']="超级管理员";
            $group['is_root']=1;
            $group['status']=1;
            $group['cd']=time();
            $group['mn_sid']=$info['id'];
            $group_id=StoreAuthGroup::instance()->add($group);
            $manager_data['cid']=$info['cid'];
            $manager_data['mn_sid']=$info['id'];
            $manager_data['account']=$info['mobile'];
            $manager_data['mid']=$mid;
            $manager_data['password']=md5(123456);
            $manager_data['name']=$info['store_name'];
            $manager_data['status']=1;
            $manager_data['group_id']=$group_id;
            $manager_data['cd']=time();
            $manager_data['md']=time();
            StoreManager::instance()->add($manager_data);
        }
        Store::instance()->edit(['id'=>$param['id']],['check_status'=>$param['op'],'check_time'=>time()]);
        return Normal::returnCode(Normal::SUC,"操作成功");
    }
    
    public function makeStoreQrcode(array $param):array {
        if(empty($param['mn_sid'])){
            return Normal::returnCode(Normal::FAIL,"店铺id不能为空");
        }
        $args = [
            'cid'   => $param['cid'],
            'mn_sid'   => $param['mn_sid'],
        ];
        $checkMember = callTcpService('makeStoreQrcode',$args);        
        if($checkMember['code']==200){
            return Normal::returnCode(Normal::SUC,"获取成功:",$checkMember['data']);
        }else{
            return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$checkMember['msg']);
        }
    }
    
     /**
     * 分销商审核列表
     * @param array $param
     * @return array
     */
    public function getStoreCheckListByPage(array $param)
    {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $p=($page-1)*$limit;
        $where=[];
        //服务商id
        if(!empty($param['sp_id'])){
            $where[]=['s.sp_id','in',$param['sp_id']];
        }
        //渠道商id
        if(!empty($param['cid'])){
            $where[]=['s.cid','in',$param['cid']];
        }
        //渠道商id
        if(!empty($param['cb_id'])){
            $where[]=['s.cb_id','in',$param['cb_id']];
        }
        //店铺名字
        if(!empty($param['mn_sid'])){
            $where[]=['s.id','in',$param['mn_sid']];
        }
        //注册手机号
        if(!empty($param['mobile'])){
            $where[]=['s.mobile','like','%'.$param['mobile'].'%'];
        }
        //注册手机号
        if(!empty($param['link_man'])){
            $where[]=['s.link_man','like','%'.$param['link_man'].'%'];
        }
        //名字或者手机模糊匹配
        if(!empty($param['search'])){
            $where[]=['s.mobile|s.store_name','like','%'.$param['search'].'%'];
        }
        //注册时间
        if(!empty($param['cd_start'])){
            $where[]=['s.cd','>=',strtotime($param['cd_start'])];
        }
        if(!empty($param['cd_end'])){
            $where[]=['s.cd','<=',strtotime($param['cd_end'])];
        }
        //状态
        if(isset($param['status']) && $param['status'] !==''){
            $where[] = ['s.status', '=', $param['status']];
        }
        //状态
        if(isset($param['check_status']) && $param['check_status'] !==''){
            $where[] = ['s.check_status', '=', $param['check_status']];
        }
        //类型
        if(!empty($param['type'])){
            $where[]=['s.type','=',$param['type']];
        }
        $fields="s.id,s.cid,s.sp_id,s.cb_id,s.mobile,s.store_name,s.status,s.check_status,s.type,s.all_sell,s.link_man,s.cd,sp.name as service_name,cb.name as channel_name,cb.level_id,s.qrcode,s.check_time,s.is_pay";
//        $level=BusinessLevel::instance()->lists(['_fields_'=>'id,level_name']);
//        $level=array_column($level,'level_name','id');
        $list=Store::instance()->alias('s')
            ->field($fields)
            ->join('service_provider sp','sp.id=s.sp_id')
            ->join('channel_business cb','cb.id=s.cb_id')
            ->where($where)
            ->order('s.id desc')
            ->limit($p, $limit)
            ->select()
            ->toArray();
        foreach ($list as $k=>$v){
//            $list[$k]['channel_level']=$level[$v['level_id']];
//            $list[$k]['type_name']=$v['type']==1?'线上商城':'O2O店铺';
//            $list[$k]['status_name']=$v['status']==1?'启用':'禁用';
            $list[$k]['check_status_name']=$v['check_status']==1?'已审核':($v['check_status']==2?'审核失败':'待审核');
//            $list[$k]['order_number']=Order::instance()->countNum(['mn_sid'=>$v['id'],'pay_status'=>1]);
//            $list[$k]['member']=StoreMember::instance()->countNum(['mn_sid'=>$v['id']]);
//            $list[$k]['vip']=StoreMember::instance()->countNum([['mn_sid','=',$v['id']],['vip_expired','>',time()]]);
            $list[$k]['cd']=date('Y-m-d H:i:s',$v['cd']);
            if($v['check_status']==0){
                $list[$k]['check_time']='';
            }else{
                $list[$k]['check_time']=$v['check_time']?date('Y-m-d H:i:s',$v['cd']):'';
            }
            if($v['check_status']==0&&$v['is_pay']==1){
                $list[$k]['display_check']=1;
            }else{
                $list[$k]['display_check']=0;
            }
            
        }
        $num=Store::instance()->alias('s')
            ->join('service_provider sp','sp.id=s.sp_id')
            ->join('channel_business cb','cb.id=s.cb_id')
            ->where($where)
            ->count();
        $data['total']=$num;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }

}

